import Vue from 'vue'
import Vuex from 'vuex'
import setting from '../setting';
Vue.use(Vuex)

const store = new Vuex.Store({
	state: {
		hasLogin: setting.mode === 'test', //true
		userInfo: {
			customerId: setting.mode === 'test' ? 718 : ''
		},
		list: [],
		cartNum: 0,
	},
	mutations: {
		login(state, provider) {
			state.hasLogin = true;
			state.userInfo = provider.userInfo;
			uni.setStorage({ //缓存用户登陆状态
				key: 'userInfo',
				data: provider.userInfo
			})

		},
		logout(state) {
			state.hasLogin = false;
			state.userInfo = {};
			uni.removeStorage({
				key: 'userInfo'
			})
		},
		addNowCart(state, provider) {
			if (state.list.length == 0) {
				state.list = [provider]
			} else {
				let found = false;
				for (let i = 0; i < state.list.length; i++) { // 遍历数组
					if (state.list[i].productId === provider.productId) { // 如果存在相同id的对象
						state.list[i].productAmount += provider.buyNum; // 数量字段加
						found = true;
						break;
					}
				}

				if (!found) { // 如果没有相同id的对象
					state.list.push(provider); // 添加新对象到数组中
				}
			}

			uni.setStorage({ //缓存用户登陆状态
				key: 'list',
				data: state.list
			})
		},
		removeNowCart(state) {
			state.list = []
			state.cartNum = 0
			uni.removeStorage({
				key: 'list'
			})
			uni.setTabBarBadge({
				index: 2,
				text: 0
			})
		}
	},
	actions: {}
})

export default store